import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../common/colors.dart';
import '../../components/custom_indicator.dart';
import 'news_list_page.dart';
import 'news_search_page.dart';


class NewsPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return NewsPageState();

  }
}

class NewsPageState extends State<NewsPage> with TickerProviderStateMixin,AutomaticKeepAliveClientMixin {

  bool get wantKeepAlive =>true;

  late TabController _tabController;

   List<String> _tabValues = ['置顶','推荐','滚动','热点','幻灯','头条','精选','公告','精彩',];

  List _topDataId = ['is_placement',
    'newsproperty_rectf1',
    'newsproperty_martf1',
    'newsproperty_hottf1',
    'newsproperty_filtf1',
    'newsproperty_tttf1',
    'newsproperty_jctf1','newsproperty_anntf1','newsproperty_jctf1',];

  FocusNode? _commentFocus;

  TextEditingController _tfEdtionController = TextEditingController();

  var topColor = [Colors.red,Colors.blue,Colors.deepOrange,Colors.yellow];


  @override
  void initState() {
    super.initState();

    _commentFocus = FocusNode();

    // requestTopData();
    _tabController = TabController(length: _tabValues.length, vsync: this, initialIndex: 0);

    _tabController.addListener(() {
      print(_tabController.index);
      setState(() {

      });
    });
  }

  // void requestTopData()async{
  //
  //   var prefs = await SharedPreferences.getInstance();
  //
  //   var params = {
  //     'access_token':prefs.getString('acctoken'),
  //     'uid':prefs.getInt('uid'),
  //     'partnet_id':prefs.getInt('partner_id'),
  //     // 'model':'cms.category',
  //     'model':'app.grid',
  //     'search':'',
  //     'search_fields':'',
  //     'fields':'name,id',
  //     'domain':"[('type', '=', 'CMS'),('parent_id.name', '=', 'DTCloud开源社区')]",
  //     'limit':'15',
  //   };
  //
  //   var result = await DioManager().rcRequset(Address.queryData,params: params);
  //   // String result = await DioUtils().post(Address.queryData,data: params);
  //   var json = jsonDecode(result);
  //
  //   List data = json['data'];
  //
  //   for(int i = 0;i<data.length;i++){
  //     print(data[i]['name']);
  //    _tabValues.add(data[i]['name']);
  //    _topDataId.add(data[i]['id']);
  //   }
  //
  //   _tabController = TabController(length: _tabValues.length, vsync: this, initialIndex: 0);
  //
  //   setState(() {
  //
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    print(_tabController.index);
    return Scaffold(

      body:Column(
        children: [
         AnimatedContainer(
           color: AppColor.themeColor,
           curve: Curves.easeIn,
           duration: Duration(milliseconds: 500),
           child: Column(
             children: [
               Container(
                   height: 35,
                   width: Get.width-15,
                   padding: EdgeInsets.only(left: 10,right: 10),
                   margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top+10),
                   // margin: EdgeInsets.only(top: 1,left: 10,right: 10),
                   // alignment: Alignment.centerLeft,
                   decoration: BoxDecoration(
                       color: Colors.white,
                       border: Border.all(width: 1, color:AppColor.lineColor),

                       borderRadius: BorderRadius.circular(7)),
                   child: Row(
                     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                     children: [
                      Row(
                        children: [
                          Icon(Icons.search,color: Colors.grey,),
                          GestureDetector(
                            onTap: (){
                              // Get.to(NewSearchPage('${_tfEdtionController.text}'));
                            },
                            child: Container(
                              // color: Colors.yellow,
                              width: Get.width/2,
                              child: TextField(
                                // enabled: false,
                                style: TextStyle(fontSize: 13),
                                focusNode: _commentFocus,
                                controller: _tfEdtionController,
                                onSubmitted: (v){
                                  print(v);
                                  Get.to(NewSearchPage(v));
                                  _commentFocus!.unfocus();
                                  _tfEdtionController.text='';
                                },
                                textInputAction: TextInputAction.search,
                                decoration: InputDecoration(
                                  isCollapsed: true,
                                  hintText: "搜索文章",
                                  hintStyle: TextStyle(fontSize: 13),

                                  // prefixIcon: Icon(Icons.search,color: Theme.of(context).primaryColor,),
                                  //去掉搜索框默认的线
                                  border: InputBorder.none,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      // GestureDetector(
                      //   child:  Container(
                      //     child: Image.asset('images/camer_icon.png',width: 21,height: 21,),
                      //   ),
                      //   onTap: (){
                      //     // Get.to(QRCodePage());
                      //   },
                      // )
                     ],
                   )
               ),
               Container(
                 margin: const EdgeInsets.only(top: 15),
                 width: Get.width,
                 decoration: BoxDecoration(
                   color: Colors.transparent,
                   borderRadius: BorderRadius.circular(0.0),
                 ),
                 child: TabBar(
                   isScrollable: true,
                   controller: _tabController,

                   labelStyle: const TextStyle(
                     fontSize: 15,),

                   labelColor: Colors.black87,

                   unselectedLabelStyle:
                   const TextStyle(fontSize: 15,),
                   unselectedLabelColor: Colors.white,
                   indicatorSize: TabBarIndicatorSize.label,

                   indicator: UnderlineTabIndicatorLi(
                       borderSide: BorderSide(
                           color: Theme.of(context).primaryColor,
                           width: 2,
                           style: BorderStyle.solid)),
                   // indicatorColor: HexColor('#567BFD'),
                   tabs: _tabValues.map((e) => Tab(text: e,)).toList(),
                   // tabs: [
                   //   Tab(
                   //     text: '账号登录',
                   //   ),
                   //   Tab(
                   //     text: '验证码登录',
                   //   ),
                   //   Tab(
                   //     text: '账号登录',
                   //   ),
                   //   Tab(
                   //     text: '验证码登录',
                   //   ),
                   //   Tab(
                   //     text: '账号登录',
                   //   ),
                   //   Tab(
                   //     text: '验证码登录',
                   //   ),
                   //   Tab(
                   //     text: '账号登录',
                   //   ),
                   //   Tab(
                   //     text: '验证码登录',
                   //   ),
                   //   Tab(
                   //     text: '验证码登录',
                   //   ),
                   // ],
                 ),
               ),
             ],
           ),
         ),

          Expanded(child:
          TabBarView(
            children: _creatBody(),
            controller: _tabController,
          ),),
        ],
      )



    );
  }

  List<Widget>_creatBody(){

    List<Widget>_page = [];

    for(int i = 0;i<_tabValues.length;i++){
      _page.add(NewsListPage(_topDataId[i]));
      // _page.add(Container());
    }
    return _page;
  }
}


//渐变透明路由动画
class FadeRouter<T> extends PageRouteBuilder<T> {
  final Widget? child;
  final int duration_ms;
  final Curve curve;
  FadeRouter(
      {this.child, this.duration_ms = 500, this.curve = Curves.fastOutSlowIn})
      : super(
      pageBuilder: (context, animation, secondaryAnimation) => child!,
      transitionDuration: Duration(milliseconds: duration_ms),
      transitionsBuilder: (context, a1, a2, child) => FadeTransition(
        opacity: Tween(begin: 0.1, end: 1.0).animate(CurvedAnimation(
          parent: a1,
          curve: curve,
        )),
        child: child,
      ));
}

